import os

from django.conf import settings
from django.contrib import admin
from django.contrib import messages
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.utils.translation import ngettext

from .models import (Media, Announcement, NativeImage, Score)


class MyMediaObstructAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):

        """
        对管理界面均生效
        """
        # 设置媒体创建者
        if not obj.media_creator:
            obj.media_creator = request.user
        obj.last_editor = request.user
        # 设置媒体名称
        if not obj.media_name:
            obj.media_name = obj.media_file.name
        # 设置媒体大小
        if not obj.media_size:
            obj.media_size = obj.filesize

        super().save_model(request, obj, form, change)


class MediaAdmin(MyMediaObstructAdmin):
    actions = ['make_published']

    @admin.action(description='更新为专升本资料分类')
    def make_published(self, request, queryset):
        updated = queryset.update(category='专升本资料')
        self.message_user(request, ngettext(
            '%d 个资源分类成功修改为专升本资料！',
            '%d 个资源分类成功修改为专升本资料！',
            updated,
        ) % updated, messages.SUCCESS)


class NativeImageAdmin(MyMediaObstructAdmin):
    pass


admin.site.register(Media, MediaAdmin)
admin.site.register(Announcement)
admin.site.register(NativeImage, NativeImageAdmin)
admin.site.register(Score)


@receiver(post_delete, sender=NativeImage)
def delete_upload_files(sender, instance, **kwargs):
    """
    删除数据库数据同时删除资源
    """
    files = getattr(instance, 'media_file')
    if not files:
        return
    fname = os.path.join(settings.MEDIA_ROOT, str(files))
    if os.path.isfile(fname):
        os.remove(fname)


# 添加监听器
@receiver(post_delete, sender=Media)
def delete_upload_files(sender, instance, **kwargs):
    """
    删除数据库数据同时删除资源
    """
    files = getattr(instance, 'media_file')
    if not files:
        return
    fname = os.path.join(settings.MEDIA_ROOT, str(files))
    if os.path.isfile(fname):
        os.remove(fname)
